package com.qc31.monitorlib.ui.listmonitor

import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import autodispose2.autoDispose
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.qc31.baselib.base.BaseActivity
import com.qc31.baselib.rx.queryThrottle
import com.qc31.baselib.utils.ActivityResultUtil.launchAct
import com.qc31.baselib.utils.ActivityResultUtil.registerResultOk
import com.qc31.baselib.utils.sub
import com.qc31.baselib.utils.toast
import com.qc31.comlib.Keys
import com.qc31.comlib.UserConstant
import com.qc31.comlib.choose.team.ChooseTeamActivity
import com.qc31.comlib.databinding.IncludeTabLayoutBinding
import com.qc31.comlib.databinding.IncludeViewpagerMatchBinding
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.ActivityMonitorListBinding
import com.qc31.monitorlib.databinding.IncludeListMonitorToolbarBinding
import com.qc31.monitorlib.databinding.IncludeMonitorEndBinding

/** @Author Jasper @Time 2020/11/11 @Desc 列表监控 */
class ListMonitorActivity :
    BaseActivity<ActivityMonitorListBinding>(ActivityMonitorListBinding::inflate) {
    private val fragments = ArrayList<Fragment>()
    private val allCarsFragment by lazy { ListMonitorFragment() }
    private val offlineFragment by lazy { ListMonitorFragment() }
    private val runCarsFragment by lazy { ListMonitorFragment() }
    private val stopCarsFragment by lazy { ListMonitorFragment() }
    private val alarmCarsFragment by lazy { ListMonitorFragment() }
    private val arrearsCarsFragment by lazy { ListMonitorFragment() }
    private val locationCarsFragment by lazy { ListMonitorFragment() }
    private val tabTitles = ArrayList<String>()
    private var mPagerAdapter: MViewPagerAdapter? = null

    private lateinit var mTabLayoutVB: IncludeTabLayoutBinding
    private lateinit var mListMonitorVB: IncludeMonitorEndBinding
    private lateinit var mViewPagerVB: IncludeViewpagerMatchBinding
    private lateinit var mMonitorBarVB: IncludeListMonitorToolbarBinding

    private val mViewModel: ListMonitorViewModel by viewModels()

    override fun initView() {
        mTabLayoutVB = IncludeTabLayoutBinding.bind(binding.root)
        mListMonitorVB = IncludeMonitorEndBinding.bind(binding.root)
        mViewPagerVB = IncludeViewpagerMatchBinding.bind(binding.root)
        mMonitorBarVB = IncludeListMonitorToolbarBinding.bind(binding.root)
        immersionBar { titleBar(mMonitorBarVB.listToolbar) }

        val stringArray: Array<String> = resources.getStringArray(R.array.tab_list_monitor)
        tabTitles.addAll(stringArray)
        mTabLayoutVB.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        initViewPager()
        initViewModel()
        initEndView()
        setListener()
    }


    private fun initViewPager() {
        fragments.add(allCarsFragment)
        fragments.add(offlineFragment)
        fragments.add(runCarsFragment)
        fragments.add(stopCarsFragment)
        fragments.add(alarmCarsFragment)
        fragments.add(arrearsCarsFragment)
        fragments.add(locationCarsFragment)
        mPagerAdapter = MViewPagerAdapter(fragments, supportFragmentManager)
        mPagerAdapter!!.setPageTitle(tabTitles)
        mViewPagerVB.mViewPager.adapter = mPagerAdapter
        mViewPagerVB.mViewPager.offscreenPageLimit = 7
        mTabLayoutVB.tabLayout.setupWithViewPager(mViewPagerVB.mViewPager)

    }

    private fun initViewModel() {
        if (UserConstant.current_car_num > 300) {
            launcher.launchAct<ChooseTeamActivity>(this) {
                putExtra("isMap", true)
            }

            mListMonitorVB.tvListAllCars.visibility = View.GONE
        } else {
            mViewModel.getCarsLocation()
        }
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)

        mViewModel.gpsObserver.observe(this) {
            if (isRefresh) toast(R.string.toast_refresh_success)
            isRefresh = false
            val titles = ArrayList<String>()
            for ((index, entity) in it.withIndex()) {
                titles.add("${tabTitles[index]}(${entity.size})")
            }
            runOnUiThread {
                mPagerAdapter!!.setPageTitle(titles)
                mPagerAdapter!!.notifyDataSetChanged()
                allCarsFragment.setData(it[0])
                offlineFragment.setData(it[1])
                runCarsFragment.setData(it[2])
                stopCarsFragment.setData(it[3])
                alarmCarsFragment.setData(it[4])
                arrearsCarsFragment.setData(it[5])
                locationCarsFragment.setData(it[6])
            }
        }
    }

    private var isRefresh = false
    override fun setListener() {
        mMonitorBarVB.ivToolbarStart.setOnClickListener {

            finish()
        }

        mMonitorBarVB.ivToolbarCenter.queryThrottle().autoDispose(scopeProvider).subscribe {
            isRefresh = true
            mViewModel.getCarsLocation()
        }

        mMonitorBarVB.ivToolbarEnd.setOnClickListener {
            if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            } else {
                binding.listDrawerLayout.openDrawer(GravityCompat.END)
            }
        }

        mListMonitorVB.tvListChooseCar.queryThrottle().autoDispose(scopeProvider).subscribe {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list)
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            launcher.launchAct<ChooseTeamActivity>(this) {
                putExtra("isMap", true)
            }

        }
        mListMonitorVB.tvListClear.queryThrottle().autoDispose(scopeProvider).subscribe {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list)
            mViewModel.isClear = true
            clearData()
        }
        mListMonitorVB.tvListAllCars.queryThrottle().autoDispose(scopeProvider).subscribe {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            mMonitorBarVB.tvToolbarTitle.setText(R.string.desc_map_all_car)
            mViewModel.isClear = false
            mViewModel.teamId = ""
            mViewModel.getCarsLocation()
        }
        mListMonitorVB.rdbListPlate.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.rdbListPlate.isChecked = true
            setPlateName(true)
            mViewModel.sortByType = "carPlate"
        }
        mListMonitorVB.rdbListCarName.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.rdbListCarName.isChecked = true
            setPlateName(false)
            mViewModel.sortByType = "carName"
        }
        mListMonitorVB.cbListTime.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListTime.isChecked = !ListMonitorModel.instance.getTimeShow()
            ListMonitorModel.instance.setTime(mListMonitorVB.cbListTime.isChecked)
            notifyFragment()
        }
        mListMonitorVB.cbListState.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListState.isChecked = !ListMonitorModel.instance.getStateShow()
            ListMonitorModel.instance.setState(mListMonitorVB.cbListState.isChecked)
            notifyFragment()
        }
        mListMonitorVB.cbListSpeed.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListSpeed.isChecked = !ListMonitorModel.instance.getSpeedShow()
            ListMonitorModel.instance.setSpeed(mListMonitorVB.cbListSpeed.isChecked)
            notifyFragment()
        }
        mListMonitorVB.cbListDriver.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListDriver.isChecked = !ListMonitorModel.instance.getDriverShow()
            ListMonitorModel.instance.setDriver(mListMonitorVB.cbListDriver.isChecked)
            notifyFragment()
        }
        mListMonitorVB.cbListMile.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListMile.isChecked = !ListMonitorModel.instance.getMileShow()
            ListMonitorModel.instance.setMile(mListMonitorVB.cbListMile.isChecked)
            notifyFragment()
        }
        mListMonitorVB.cbListRunStop.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListRunStop.isChecked = !ListMonitorModel.instance.getRunStopShow()
            ListMonitorModel.instance.setRunStop(mListMonitorVB.cbListRunStop.isChecked)
            notifyFragment()
        }

        binding.listDrawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
            override fun onDrawerClosed(drawerView: View) {
                super.onDrawerClosed(drawerView)
                mMonitorBarVB.ivToolbarEnd.isSelected = false
            }

            override fun onDrawerOpened(drawerView: View) {
                super.onDrawerOpened(drawerView)
                mMonitorBarVB.ivToolbarEnd.isSelected = true
            }
        })

    }

    private fun notifyFragment() {
        allCarsFragment.notifyDataSetChanged()
        offlineFragment.notifyDataSetChanged()
        runCarsFragment.notifyDataSetChanged()
        stopCarsFragment.notifyDataSetChanged()
        alarmCarsFragment.notifyDataSetChanged()
        arrearsCarsFragment.notifyDataSetChanged()
        locationCarsFragment.notifyDataSetChanged()
    }

    //设置是否是车牌排序
    private fun setPlateName(isPlate: Boolean) {
        allCarsFragment.setPlatName(isPlate)
        offlineFragment.setPlatName(isPlate)
        runCarsFragment.setPlatName(isPlate)
        stopCarsFragment.setPlatName(isPlate)
        alarmCarsFragment.setPlatName(isPlate)
        arrearsCarsFragment.setPlatName(isPlate)
        locationCarsFragment.setPlatName(isPlate)
    }

    private fun clearData() {
        mViewModel.teamId = ""
        mPagerAdapter!!.setPageTitle(tabTitles)
        mPagerAdapter!!.notifyDataSetChanged()
        allCarsFragment.clear()
        offlineFragment.clear()
        runCarsFragment.clear()
        stopCarsFragment.clear()
        alarmCarsFragment.clear()
        arrearsCarsFragment.clear()
        locationCarsFragment.clear()
    }

    private fun initEndView() {
        val isPlate = mViewModel.sortByType == "carPlate"
        setPlateName(isPlate)
        mListMonitorVB.rdbListPlate.isChecked = isPlate
        mListMonitorVB.rdbListCarName.isChecked = mViewModel.sortByType == "carName"
        mListMonitorVB.cbListTime.isChecked = ListMonitorModel.instance.getTimeShow()
        mListMonitorVB.cbListState.isChecked = ListMonitorModel.instance.getStateShow()
        mListMonitorVB.cbListSpeed.isChecked = ListMonitorModel.instance.getSpeedShow()
        mListMonitorVB.cbListDriver.isChecked = ListMonitorModel.instance.getDriverShow()
        mListMonitorVB.cbListMile.isChecked = ListMonitorModel.instance.getMileShow()
        mListMonitorVB.cbListRunStop.isChecked = ListMonitorModel.instance.getRunStopShow()
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val teamId = it.getStringExtra(Keys.INTENT_TEAM_ID) ?: ""
            val teamName = it.getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""
//                val carNum = it.getStringExtra(Keys.INTENT_TEAM_NUM)?:"0"
            mViewModel.isClear = false
            mViewModel.teamId = teamId
            mViewModel.getCarsLocation()
            mMonitorBarVB.tvToolbarTitle.text = "${sub(teamName, 10)}"
            mViewPagerVB.mViewPager.currentItem = 0
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}


class MViewPagerAdapter(private val fragments: ArrayList<Fragment>, manager: FragmentManager) :
    FragmentStatePagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    private var tabTitles = ArrayList<String>()
    override fun getCount(): Int {
        return fragments.size
    }


    override fun getPageTitle(position: Int): CharSequence {
        return tabTitles[position]
    }

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    fun setPageTitle(tabTitles: ArrayList<String>) {
        this.tabTitles = tabTitles

    }
}